package com.mark.web.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mark.common.ServerResponse;
import com.mark.web.sys.entity.po.UserImg;
import com.mark.web.sys.entity.vo.UserImgVo;
import com.mark.web.sys.mapper.UserImgMapper;
import com.mark.web.sys.service.IUserImgService;
import com.mark.web.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 用户头像POJO类
 * @Author: Mark
 * @CreateDate: 2019/1/12 12:08
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 */
@Service(value = "sysIUserImgService")
public class UserImgServiceImpl implements IUserImgService {
    private final UserImgMapper userImgMapper;
    private final IUserService IUserService;

    @Autowired
    public UserImgServiceImpl(UserImgMapper userImgMapper, IUserService iUserService) {
        this.userImgMapper = userImgMapper;
        IUserService = iUserService;
    }

    @Override
    public ServerResponse<PageInfo<UserImgVo>> getUserImageList(int pageNum, int pageSize, Integer currentUserId) {
        PageHelper.startPage(pageNum,pageSize);
        List<UserImg> userImgList = userImgMapper.selectListByUserId(currentUserId);
        List<UserImgVo> userImgVoList = Lists.newArrayList();
        for (UserImg userImg: userImgList){
            userImgVoList.add(new UserImgVo(userImg));
        }
        PageInfo<UserImgVo> userImgPageInfo = new PageInfo<>(userImgVoList);
        return ServerResponse.createBySuccess(userImgPageInfo);
    }

    @Transactional(value = "myShrioTransactionManager",rollbackFor = Exception.class)
    @Override
    public ServerResponse<String> addImage(String imageUrl, Integer currentUserId) {
        //保存用户头像信息
        UserImg userImg = new UserImg();
        userImg.setUrl(imageUrl);
        userImg.setUserId(currentUserId);
        userImg.setEnableStatus(1);
        userImg.setPriority(0);
        int result = userImgMapper.insert(userImg);

        //更新当前用户的头像.
        IUserService.updateImageUrl(currentUserId, imageUrl);
        if (result == 1) {
            return ServerResponse.createBySuccessMessage("上传头像到用户头像表成功");
        }
        return ServerResponse.createByErrorMessage("上传头像到用户头像表失败");
    }
}
